package com.yazi.mxz.common.service.impl;


import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.exception.MyIllegalArgumentException;
import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;
import com.yazi.mxz.common.db.dao.CategoryDao;
import com.yazi.mxz.common.db.dao.GoodsDao;
import com.yazi.mxz.common.db.dao.StoreGoodsDao;
import com.yazi.mxz.common.entity.ValueFactory;
import com.yazi.mxz.common.entity.beans.Category;
import com.yazi.mxz.common.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends BasicService<Category> implements CategoryService {
	private static Logger log = LoggerFactory.getLogger(CategoryServiceImpl.class);
	
	@Resource
	CategoryDao categoryDao;
	@Resource
	StoreGoodsDao storeGoodsDao;
	@Resource
	GoodsDao goodsDao;

	@Override
	protected Dao<Category> getDao() {
		return categoryDao;
	}
	
	@Override
	public Category addOrEdit(Category category) throws MyException {
		Long catId = category.getCatId();
		
		if(null != catId && catId > 0){
			
			log.debug("addOrModify->modify: catId={}", catId);
			Category destCategory = categoryDao.get(catId);
			destCategory = ValueFactory.combine(category, destCategory);
			destCategory.setUpdateTime(DateUtil.getTimeStamp());
			categoryDao.merge(destCategory);
			return destCategory;
			
		}else {
			
			log.debug("addOrModify->add: name={}", category.getName());
			category = ValueFactory.validate(category);
			Category parentCat = null;
			if (null != category.getCategory() && null != category.getCategory().getCatId()) {
				parentCat = categoryDao.get(category.getCategory().getCatId());
			} 
			if (null == parentCat) {
				throw new MyIllegalArgumentException();
			}
			category.setType(parentCat.getType());
			category.setDeep(parentCat.getDeep() + 1);
			category.setUpdateTime(DateUtil.getTimeStamp());			
			category.setCatId(null);
			categoryDao.persist(category);
			return category;
			
		}
	}

	@Override
	public void removeByAdmin(long delId, long bakupId) {
		log.debug("removeByAdmin : delId={}, bakupId={}", delId, bakupId);
		// 移动商品
		storeGoodsDao.moveByCatId(delId, bakupId);
		goodsDao.moveByCatId(delId, bakupId);
		
		// 删除系统类目
		categoryDao.delete(delId);
	}
}
